package com.skyable.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;
import java.util.function.Function;

/**
 * @author GaoYuan
 * @title: JwtTokenUtil
 * @projectName spring-cloud-demo
 * @description: JWT工具类
 * @date 2021/3/718:31
 */
public class JwtTokenUtil {

    private static final long JWT_TOKEN_VALIDITY = 7 * 24 * 60 * 60;
    private static final String JWT_SECRET = "ablecloud@skyable";

    /**
     * 根据token获取用户名
     * @param token
     * @return
     */
    public static String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    /**
     * 根据token获取过期时间
     * @param token
     * @return
     */
    public static Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }
    public static <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static Claims getAllClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(JWT_SECRET).parseClaimsJws(token).getBody();
    }

    /**
     * 判断token是否过期
     * @param token
     * @return
     */
    private static Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    /**
     * 生成token
     * @param userName
     * @param claims
     * @return
     */
    public static String generateToken(String userName,Map<String, Object> claims) {
        return doGenerateToken(claims, userName);
    }

    /**
     * 生成用户token
     * @param claims
     * @param subject
     * @return
     */
    private static String doGenerateToken(Map<String, Object> claims, String subject) {
        return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000))
                .signWith(SignatureAlgorithm.HS512, JWT_SECRET).compact();
    }

    /**
     * 验证用户token
     * @param token
     * @param userName
     * @return
     */
    public static Boolean validateToken(String token, String userName) {
        final String jwtUserName = getUsernameFromToken(token);
        return (jwtUserName.equals(userName) && !isTokenExpired(token));
    }
}
